#!/usr/bin/env python
# -*- coding: utf-8 -*-

import sys, os
from datetime import datetime
import time
import mysql.connector
import xlrd3
import xlwt3

def GetData(config, stmt_select):
    db = mysql.connector.Connect(**config)
    cursor = db.cursor()
    cursor.execute(stmt_select)
    row = cursor.fetchall()
    cursor.close()
    db.close()
    return row
def WriteData(data):
    wb = xlwt3.Workbook()
    ws = wb.add_sheet('result')
    #for i in range(0, len(data)):
    i = 0
    for i in range(0, len(data)):
        ws.write(i, 0, data[i][0])
    wb.save('Statistics.xls')
def readSection(lines, start, endflag):
    ''' 读取一个版块的所有选项 '''
    temp = list()
    for j in range(start, len(lines)):
        if lines[j][0] == '#' or lines[j][0] == ' ' or lines[j][0] == '\n':
                    continue
        if lines[j][0] == endflag:
            i = j
            break
        if lines[j][-1] == '\n':
            lines[j] = lines[j][0:-1]
        temp.append(lines[j])
    return temp
def GetSqlStm():
    ''' 读取配置文件 '''
    # 读取配置文件
    FILE_NAME = "sqlStm.ini"
    # 读出整个配置文件  所有行
    cfobj = open(FILE_NAME, "r")
    lines = cfobj.readlines()
    cfobj.close()
    select_stm = list()
    for i in range(0, len(lines)):
        # 忽略注释 和 空行
        if lines[i][0] == '#' or lines[i][0] == ' ' or lines[i][0] == '\n':
            continue
        # 去掉行尾换行符
        if lines[i][-1] == '\n':
            lines[i] = lines[i][0:-1]
        if lines[i] == "[SELECT_STM]":
            select_stm = readSection(lines, i + 1, '[')
    return select_stm

import config
config = config.Config.dbinfo().copy()
sql = GetSqlStm()
for s in sql:
    print(s)
row = GetData(config, sql[0])
for r in row:
    print("%s\n" % (r))
WriteData(row)
